import os
import time
import threading
import requests
import logging
from datetime import datetime
from flask_socketio import SocketIO
from utils import setup_logger, get_log_dir


class WvpMediaManager:
    def __init__(self, socketio=None):
        self.socketio = socketio
        self.logger = setup_logger()
        self.running = False
        self.stop_event = threading.Event()
        self.stats = {"total_loops": 0, "success_count": 0, "failure_count": 0}
        self.thread = None
        self.log_dir = get_log_dir()
        self.domain = ""

    def log(self, message):
        """记录消息到日志文件并通过Socket发送"""
        self.logger.info(message)
        if self.socketio:
            self.socketio.emit("wvp_log", {"message": message})

    def start_test(
        self,
        device_ids,
        max_loops=100,
        access_token="",
        media_check_url="",
        check_interval=5,
        domain="",
    ):
        self.domain = domain
        """启动WVP启停流测试"""
        if self.running:
            return False, "测试已在运行中"

        if not device_ids:
            return False, "设备ID列表不能为空"

        if not access_token:
            return False, "Access Token不能为空"

        if not media_check_url:
            return False, "媒体检测URL不能为空"

        # 重置统计信息
        self.stats = {"total_loops": 0, "success_count": 0, "failure_count": 0}

        # 创建线程
        self.stop_event.clear()
        self.thread = threading.Thread(
            target=self.run_test_loop,
            args=(device_ids, max_loops, access_token, media_check_url, check_interval),
            daemon=True,
        )

        self.thread.start()
        self.running = True
        self.log("WVP测试已启动")
        self.update_status()
        return True, "WVP测试已启动"

    def stop_test(self):
        """停止WVP启停流测试"""
        if self.running:
            self.stop_event.set()
            self.running = False
            self.log("WVP测试停止中...")
            self.update_status()

    def start_play(self, device_id, headers):
        """启动拉流并检查返回结果"""
        try:
            url = f"{self.domain}/api/play/start/{device_id}/{device_id}"
            response = requests.get(url, headers=headers)

            # 检查返回的JSON
            if response.status_code == 200:
                json_data = response.json()
                code = json_data.get("code", -1)
                msg = json_data.get("msg", "")

                # 新增：检查是否收流超时
                if code == -2 and "收流超时" in msg:
                    self.log(
                        f"[START] device_id={device_id}, 状态码: {response.status_code}, code={code}, msg={msg}"
                    )
                    return {"success": False, "timeout": True, "code": code, "msg": msg}

                success = code == 0
                self.log(
                    f"[START] device_id={device_id}, 状态码: {response.status_code}, "
                    f"code={code}, msg={msg}, 成功: {success}"
                )
                return {"success": success, "timeout": False, "code": code, "msg": msg}
            else:
                self.log(
                    f"[START] device_id={device_id}, 状态码: {response.status_code}, 非200响应"
                )
                return {
                    "success": False,
                    "timeout": False,
                    "code": response.status_code,
                    "msg": f"HTTP状态码: {response.status_code}",
                }
        except Exception as e:
            self.log(f"[START] device_id={device_id}, 请求失败: {e}")
            return {"success": False, "timeout": False, "code": -999, "msg": str(e)}

    def stop_play(self, device_id, headers):
        """停止拉流"""
        try:
            url = f"{self.domain}/api/play/stop/{device_id}/{device_id}"
            response = requests.get(url, headers=headers)
            success = response.status_code == 200
            self.log(
                f"[STOP] device_id={device_id}, 状态码: {response.status_code}, 成功: {success}"
            )
            return success
        except Exception as e:
            self.log(f"[STOP] device_id={device_id}, 请求失败: {e}")
            return False

    def check_media_list(self, media_check_url):
        """检查媒体列表"""
        try:
            response = requests.get(media_check_url)
            json_data = response.json()
            code = json_data.get("code", -1)
            msg = json_data.get("msg", "")
            data = json_data.get("data")

            self.log(f"[CHECK] code={code}, msg={msg}")

            # 关键错误
            if code == -400 or "RtmpMediaSourceMuxer" in msg:
                self.log("❌ 检测失败：code=-400 或 msg 包含 RtmpMediaSourceMuxer")
                return -400

            # 成功
            if code == 0 and data:
                self.log("✅ 检测成功：code=0 且 data 有内容")
                return 0
            elif code == 0 and not data:
                self.log("⚠️ code=0 但 data 为空")
                return -2
            else:
                self.log(f"⚠️ 异常返回 code={code}")
                return code

        except Exception as e:
            self.log(f"[CHECK] 请求失败: {e}")
            return -999

    def update_status(self):
        """更新状态到客户端"""
        if self.socketio:
            self.socketio.emit(
                "wvp_status",
                {
                    "running": self.running,
                    "stats": {
                        "totalLoops": self.stats["total_loops"],
                        "successCount": self.stats["success_count"],
                        "failureCount": self.stats["failure_count"],
                    },
                },
            )

    def run_test_loop(
        self, device_ids, max_loops, access_token, media_check_url, check_interval
    ):
        """执行测试循环"""
        headers = {
            "Accept": "application/json, text/plain, */*",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
            "access-token": access_token,
            "Referer": self.domain,
            "Origin": self.domain,
        }

        start_time = datetime.now()
        device_index = 0
        loop_count = 0

        self.log(f"开始WVP测试，设备数: {len(device_ids)}, 最大循环次数: {max_loops}")

        while not self.stop_event.is_set() and loop_count < max_loops:
            device_id = device_ids[device_index]
            loop_count += 1
            self.stats["total_loops"] += 1

            self.log(f"第 {loop_count}/{max_loops} 轮，设备ID: {device_id}")

            # 启动拉流并获取详细结果
            start_result = self.start_play(device_id, headers)

            # 新增：检查是否收流超时
            if start_result.get("timeout", False):
                self.stats["failure_count"] += 1
                self.log(f"❌ 收流超时，直接标记为失败")
                self.update_status()
                device_index = (device_index + 1) % len(device_ids)
                continue  # 跳过后续检查

            if not start_result["success"]:
                self.stats["failure_count"] += 1
                self.update_status()
                device_index = (device_index + 1) % len(device_ids)
                continue

            time.sleep(1)

            # 检查媒体列表
            check_result = self.check_media_list(media_check_url)
            time.sleep(0.5)
            check_result = self.check_media_list(media_check_url)
            time.sleep(0.5)
            check_result = self.check_media_list(media_check_url)

            # 更新统计
            if check_result == 0:
                self.stats["success_count"] += 1
            else:
                self.stats["failure_count"] += 1

            # 停止拉流
            self.stop_play(device_id, headers)

            # 更新状态
            self.update_status()

            # 等待间隔
            time.sleep(check_interval)
            device_index = (device_index + 1) % len(device_ids)

        # 测试结束
        duration = datetime.now() - start_time
        self.log(f"WVP测试完成，总循环次数: {loop_count}, 耗时: {duration}")
        self.log(
            f"成功次数: {self.stats['success_count']}, 失败次数: {self.stats['failure_count']}"
        )
        self.running = False
        self.update_status()
